import 'dart:convert';

import 'package:cave_flutter/config/whl_global_config.dart';
import 'package:cave_flutter/style/whl_style.dart';
import 'package:crypto/crypto.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:intl/intl.dart';

import 'package:http_parser/http_parser.dart';

extension StringExtension on String {
  int? toIntOrNull() {
    return int.tryParse(this);
  }

  double? toDoubleOrNull() {
    return double.tryParse(this);
  }

  num? toNumOrNull() {
    return num.tryParse(this);
  }

  ///set text to clipboard
  Future<void> setData() {
    String text = this;
    return Clipboard.setData(ClipboardData(text: text));
  }

  String ifEmpty(String Function() function) {
    String value = this;
    if (value.isEmpty) return value;
    return function();
  }

  ///Emoji
  String filterEmoji() {
    String content = this;
    RegExp regexp = RegExp(
        "[^\\u0020-\\u007E\\u00A0-\\u00BE\\u2E80-\\uA4CF\\uF900-\\uFAFF\\uFE30-\\uFE4F\\uFF00-\\uFFEF\\u0080-\\u009F\\u2000-\\u201f\r\n]");
    return content.replaceAll(regexp, "");
  }

  ///Emoji
  bool containsEmoji() {
    String content = this;
    RegExp regexp = RegExp(
        "[^\\u0020-\\u007E\\u00A0-\\u00BE\\u2E80-\\uA4CF\\uF900-\\uFAFF\\uFE30-\\uFE4F\\uFF00-\\uFFEF\\u0080-\\u009F\\u2000-\\u201f\r\n]");
    return content.contains(regexp);
  }

  String generateMd5() {
    var content = const Utf8Encoder().convert(this);
    var digest = md5.convert(content);
    return digest.toString();
  }

  ///
  String toCiphertext() {
    return replaceAll(RegExp(r"[\s\S]"), "*");
  }

  ///
  String hideMobile() {
    String mobile = this;
    if (11 == mobile.length) {
      return "${mobile.substring(0, 3)}****${mobile.substring(mobile.length - 4, mobile.length)}";
    }
    return mobile;
  }

  bool isStrongPassword() {
    if (this.length < 8 || this.length > 30) {
      return false;
    }
    RegExp regexp1 = RegExp(".*\\d+.*");
    bool match1 = regexp1.hasMatch(this);
    if (!match1) {
      return false;
    }

    RegExp regexp2 = RegExp(".*[a-z]+.*");
    bool match2 = regexp2.hasMatch(this);
    if (!match2) {
      return false;
    }
    RegExp regexp3 = RegExp(".*[A-Z]+.*");
    bool match3 = regexp3.hasMatch(this);
    if (!match3) {
      return false;
    }

    RegExp regexp4 = RegExp(".*[`.~!@#%^&*()_+<>?:]+.*");
    bool match4 = regexp4.hasMatch(this);
    if (!match4) {
      return false;
    }
    return true;
  }

  String toImageUrl() {
    if (isEmpty) {
      return "";
    } else if (contains("http")) {
      return this;
    } else {
      if (startsWith("/")) {
        return "${WHLGlobalConfig.getInstance().getImageBaseUrl()}$this";
      }
      return "${WHLGlobalConfig.getInstance().getImageBaseUrl()}/$this";
    }
  }

  MediaType getMediaType() {
    switch (this.toLowerCase()) {
      case "jpg":
      case "jpeg":
      case "jpe":
        return MediaType("image", "jpeg");
      case "png":
        return new MediaType("image", "png");
      case "bmp":
        return MediaType("image", "bmp");
      case "gif":
        return MediaType("image", "gif");
      case "json":
        return MediaType("application", "json");
      case "svg":
      case "svgz":
        return MediaType("image", "svg+xml");
      case "mp3":
        return MediaType("audio", "mpeg");
      case "mp4":
        return MediaType("video", "mp4");
      case "mov":
        return MediaType("video", "mov");
      case "htm":
      case "html":
        return MediaType("text", "html");
      case "css":
        return MediaType("text", "css");
      case "csv":
        return MediaType("text", "csv");
      case "txt":
      case "text":
      case "conf":
      case "def":
      case "log":
      case "in":
        return MediaType("text", "plain");
      case "xls":
      case "xlsx":
        return MediaType("application", "x-xls");
      case "pdf":
        return MediaType("application", "pdf");
      case "doc":
      case "docx":
        return MediaType("application", "msword");
      case "mp3":
        return MediaType("audio", "mp3");
    }
    return MediaType("application", "octet-stream");
  }

  String getDocImageName() {
    String imageName = "attachment_txt.png";

    if (this.contains("txt")) {
      imageName = "attachment_txt.png";
    } else if (this.contains("pdf")) {
      imageName = "attachment_pdf.png";
    } else if (this.contains("rtf") ||
        this.contains("doc") ||
        this.contains("docx")) {
      imageName = "attachment_word.png";
    } else if (this.contains("xls") || this.contains("xlsx")) {
      imageName = "attachment_xsl.png";
    } else if (this.contains("mp4") || this.contains("video")) {
      imageName = "attachment_video.png";
    }

    return imageName;
  }

  String toDateStringWithFormat(String format) {
    if (this.isEmpty) return "";
    DateTime dateTime = DateTime.parse(this).toLocal();
    DateFormat dateFormat = DateFormat(format);
    String dateStr = dateFormat.format(dateTime);

    return dateStr;
  }

  String capitalize1() {
    if (this.isEmpty) return this;
    return this[0].toUpperCase() + this.substring(1);
  }

  ls_dealWithNikeName() {
    String showName = "";
    String tempName = this;

    String text1 = this.formatNameSeparatedByString("-");
    String text2 = this.formatNameSeparatedByString("(");
    String text3 = this.formatNameSeparatedByString(" ");

    if (text1.isNotEmpty) {
      tempName = text1;
    } else if (text2.isNotEmpty) {
      tempName = text2;
    } else if (text3.isNotEmpty) {
      tempName = text3;
    }
    if (tempName.length >= 2) {
      showName = tempName.substring(0, 2);
    }
    return showName.toUpperCase();
  }

  formatNameSeparatedByString(String sepStr) {
    if (!this.contains(sepStr)) return "";
    List spList = this.split(sepStr);
    List resultList = [];
    spList.forEach((element) {
      if (element.isNotEmpty) {
        resultList.add(element);
      }
    });
    if (resultList.length > 1) {
      String firstName = resultList.first;
      String lastName = resultList.last;
      return "${firstName.substring(0, 1)}${lastName.substring(0, 1)}";
    } else {
      return resultList.first;
    }
  }

  call() {
    // launchUrlString("tel:${this}");
  }

  sendEmail() {
    // launchUrlString("mailto:${this}");
  }

  ///searchContent    输入的搜索内容
  ///frontContent     需要另外添加在最前面的文字
  ///fontSize         需要显示的字体大小
  ///fontColor        需要显示的正常字体颜色
  ///selectFontColor  需要显示的搜索字体颜色
  List<TextSpan> getTextSpanList(
      {String searchContent = '',
      String frontContent = '',
      double fontSize = 14,
      Color fontColor = Colors.black,
      Color selectFontColor = Colors.red}) {
    List<TextSpan> textSpanList = [];

    if (frontContent.isNotEmpty) {
      textSpanList.add(TextSpan(
          text: frontContent,
          style: TextStyle(fontSize: fontSize, color: fontColor)));
    }
    String textContent = this;

    ///搜索内容不为空并且 显示内容中存在与搜索内容相同的文字
    if (searchContent.isNotEmpty && textContent.contains(searchContent)) {
      List<Map> strMapList = [];
      bool isContains = true;
      while (isContains) {
        int startIndex = textContent.indexOf(searchContent);
        String showStr = textContent.substring(
            startIndex, startIndex + searchContent.length);
        Map strMap;
        if (startIndex > 0) {
          String normalStr = textContent.substring(0, startIndex);
          strMap = {};
          strMap['content'] = normalStr;
          strMap['isHighlight'] = false;
          strMapList.add(strMap);
        }
        strMap = {};
        strMap['content'] = showStr;
        strMap['isHighlight'] = true;
        strMapList.add(strMap);
        textContent = textContent.substring(
            startIndex + searchContent.length, textContent.length);

        isContains = textContent.contains(searchContent);
        if (!isContains && textContent != '') {
          strMap = {};
          strMap['content'] = textContent;
          strMap['isHighlight'] = false;
          strMapList.add(strMap);
        }
      }
      for (var map in strMapList) {
        textSpanList.add(TextSpan(
            text: map['content'],
            style: TextStyle(
                fontSize: fontSize,
                color: map['isHighlight'] ? selectFontColor : fontColor)));
      }
    } else {
      ///正常显示所有文字
      textSpanList.add(TextSpan(
        text: textContent,
        style: TextStyle(fontSize: fontSize, color: fontColor),
      ));
    }
    return textSpanList;
  }

  String get capitalize => "${this[0].toUpperCase()}${this.substring(1)}";
  String get capitalizeFullStop =>
      "${this.split('. ').map((sentence) => sentence.capitalize).join('. ')}";
  String get capitalizeQuestionMark =>
      "${this.split('? ').map((sentence) => sentence.capitalize).join('? ')}";
  String get capitalizeExclamationMark =>
      "${this.split('! ').map((sentence) => sentence.capitalize).join('! ')}";
  String get capitalizeSentences =>
      "${this.capitalizeFullStop.capitalizeQuestionMark.capitalizeExclamationMark}";
}
